<?php

class ClassesController extends GxController {

    public function filters() {
        return array('rights');
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id, 'Classes'),
        ));
    }

    protected function saveClass($model, $recordtype) {
        $classtags = '';
        $classTagText = '';
        if (isset($_POST['Classes'])) {
            $classtag = $_POST['Classes']['class_tag'];
            foreach ($classtag as $key => $value) {
                $classTag = ClassCourseTags::model()->findByPk($value);
                $classTagText .=$classTag->tag_name . ',';
                $classtags.=$value . ',';
            }

            $model->setAttributes($_POST['Classes']);
            $model->setAttribute('status', SkillConfig::STATUS_ACTIVE);
            $model->setAttribute('class_tag_description', $classTagText);
            $model->setattribute('class_tag', $classtags);

            if (!empty($_POST['Classes']['users_id'])) {
                $model->setAttribute('users_id', $_POST['Classes']['users_id']);
            } else {
                $model->setAttribute('backend_user_id', getLoginUserId());
            }
            if ($model->isNewRecord) {
                $authKey = time() . guid();
                $model->setAttribute('auth_key', $authKey);
                $createupdatetime = 'create_time';
            } else {
                $createupdatetime = 'update_time';
            }

            $model->setAttribute($createupdatetime, SkillConfig::CreateDateTime());
            $transaction = Yii::app()->getDb()->beginTransaction();
            try {
                if ($model->save(false)) {
                    $this->saveVenueAddress($model, $recordtype);
                    self::setclassTargetAudienceType($model);
                    self::saveClassFunLearning($model);
                    self::saveClassTicketBooked($model);
                    $save = self::addClassImage($model);
                    Yii::app()->user->setState('images', null);
                    $save = SkillConfig::STATUS_ACTIVE;
                }
                $transaction->commit();
                if ($save) {
                    Yii::app()->user->setState('trainer_id', NULL);
                    /* Sending mails to subscriber */
                    if ($recordtype == 'new') {
                        $this->SendmailToUserByNewUpdateClassNotification($model, $recordtype, '');
                    }
                    /* Sending mails to subscriber */
                    if (Yii::app()->getRequest()->getIsAjaxRequest())
                        Yii::app()->end();
                    $this->redirect(array('admin'));
                }
            } catch (Exception $e) {
                $transaction->rollback();
                throw $e;
            }
        }
    }

    private static function setclassTargetAudienceType($model) {
        (!$model->isNewRecord) ? Classes::deleteClassesTargetAudience($model->id) : '';
        if (isset($_POST['TargetAudience']['classesTargetAudiences']) && !empty($_POST['TargetAudience']['classesTargetAudiences'])) {
            foreach ($_POST['TargetAudience']['classesTargetAudiences'] as $targetAudience) {
                $modelClassTargetAudience = new ClassesTargetAudience();
                $modelClassTargetAudience->target_audience_id = $targetAudience;
                $modelClassTargetAudience->classes_id = $model->id;
                $modelClassTargetAudience->save(false);
            }
        }
    }

    protected function saveVenueAddress($model, $recordtype) {
        $BeforeUpdateclassWithVenue = '';
        $BeforeUpdateclassBatch = '';
        $BeforeUpdateclassVenueBatch = '';
        if (!$model->isNewRecord) {
            $updateInformationClass[] = 'Class';
            /* getting information regarding class for mail */
            $AllvenueId = classes::getclassWithVenues($model->id);
            foreach ($AllvenueId as $value) {
                $BeforeUpdateclassWithVenue[] = $value['class_venue_id'];
                $BeforeUpdateclassBatch = classes::getClassBatch($model->id, $value['class_venue_id']);
                foreach ($BeforeUpdateclassBatch as $key => $value) {
                    $BeforeUpdateBatchStartDate[] = $value['start_date'];
                    $BeforeUpdateBatchStartTime[] = $value['start_time'];
                    $BeforeUpdateBatchEndTime[] = $value['end_time'];
                    $BeforeUpdateBatchPrice[] = $value['price'];
                    $BeforeUpdateBatchSeats[] = $value['seats'];
                    /* $classEarlyDiscount = classes::getClassBatchEarlyBirdDiscount($model->id, $value['id']);
                      $classGroupDiscount = classes::getClassBatchGroupDscount($model->id, $value['id']);
                      foreach ($classEarlyDiscount as $earlykey => $earlyvalue) {
                      $BeforeUpdateclassVenueBatchEarlyDiscount[$earlykey][] = $earlyvalue;
                      }
                      foreach ($classGroupDiscount as $groupdiscountkey => $groupdiscountvalue) {
                      $BeforeUpdateclassVenueBatchGroupDiscount[$groupdiscountkey][] = $groupdiscountvalue;
                      } */
                }
            }

            Classes::deleteClassesWithVenue($model->id);
            Classes::deleteClassesBatches($model->id);
            Classes::deleteClassesBatcheEarlyDiscount($model->id);
            Classes::deleteClassesBatcheGroupDiscount($model->id);
            Classes::deleteClassesBatcheSessions($model->id);
            Classes::deleteClassesStructure($model->id);
            Classes::deleteclassbatchweelymonthly($model->id);
        }
        /**         * *********** save venue **************** */
        if (isset($_POST['ClassVenue']['name'])) {
            for ($venukey = 0; $venukey < count($_POST['ClassVenue']['name']); $venukey++) {
                /*                 * ************ save class with venue **************** */
                if (isset($_POST['ClassVenue']['venueId'][$venukey]) && !empty($_POST['ClassVenue']['venueId'][$venukey])) {
                    $classWithVenue = new ClassWithVenue;
                    $classWithVenue->setAttribute('classes_id', $model->id);
                    $classWithVenue->setAttribute('class_venue_id', $_POST['ClassVenue']['venueId'][$venukey]);
                    $classWithVenue->save(false);
                    $venueId = $_POST['ClassVenue']['venueId'][$venukey];
                } else {
                    $modelClassVenue = new ClassVenue;
                    $modelClassVenue->setAttribute('name', $_POST['ClassVenue']['name'][$venukey]);
                    $modelClassVenue->setAttribute('address_line1', $_POST['ClassVenue']['address_line1'][$venukey]);
                    $modelClassVenue->setAttribute('address_line2', $_POST['ClassVenue']['address_line2'][$venukey]);
                    $modelClassVenue->setAttribute('venue_locality', $_POST['ClassVenue']['venue_locality'][$venukey]);
                    $modelClassVenue->setAttribute('zip_code', $_POST['ClassVenue']['zip_code'][$venukey]);
                    $modelClassVenue->setAttribute('country_id', $_POST['ClassVenue']['country_id'][$venukey]);
                    $modelClassVenue->setAttribute('state_id', $_POST['ClassVenue']['state_id'][$venukey]);
                    $modelClassVenue->setAttribute('city_id', $_POST['ClassVenue']['city_id'][$venukey]);
                    if (!empty($model->users_id)) {
                        $modelClassVenue->setAttribute('users_id', $model->users_id);
                    } else {
                        $modelClassVenue->setAttribute('backend_user_id', $model->backend_user_id);
                    }

                    $modelClassVenue->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                    $modelClassVenue->setAttribute('create_time', SkillConfig::CreateDateTime());
                    $modelClassVenue->save(false);
                    $classWithVenue = new ClassWithVenue;
                    $classWithVenue->setAttribute('classes_id', $model->id);
                    $classWithVenue->setAttribute('class_venue_id', $modelClassVenue->id);
                    $classWithVenue->save(false);
                    $venueId = $modelClassVenue->id;
                }
                $venueIndex = $_POST['venueIndex'][$venukey];
                if ($recordtype == "update") {
                    if (!in_array($venueId, $BeforeUpdateclassWithVenue)) {
                        $updateInformationClass[] = "Venue";
                    }
                }

                /*                 * ************ save batches according to venue **************** */
                if (isset($_POST['batchIndex'][$venueIndex])) {
                    for ($batchKey = 0; $batchKey < count($_POST['batchIndex'][$venueIndex]); $batchKey++) {
                        if (isset($_POST['ClassBatch']['ClassVenue'][$venueIndex]['seats'][$batchKey])) {
                            $modelClassBatch = new ClassBatch;
                            $modelClassBatch->setAttribute('start_date', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['start_date'][$batchKey]);
                            $modelClassBatch->setAttribute('start_time', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['start_time'][$batchKey]);
                            $modelClassBatch->setAttribute('end_time', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['end_time'][$batchKey]);
                            $modelClassBatch->setAttribute('price', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['price'][$batchKey]);
                            $modelClassBatch->setAttribute('seats', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['seats'][$batchKey]);
                            $modelClassBatch->setAttribute('schedule_id', $_POST['ClassBatch']['ClassVenue'][$venueIndex]['schedule_id'][$batchKey]);
                            $modelClassBatch->setAttribute('classes_id', $model->id);
                            $modelClassBatch->setAttribute('class_venue_id', $venueId);
                            $modelClassBatch->save(false);
                            $batchIndex = $_POST['batchIndex'][$venueIndex][$batchKey];
                            if ($recordtype == "update") {
                                if ((!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['start_date'][$batchKey], $BeforeUpdateBatchStartDate)) || (!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['start_time'][$batchKey], $BeforeUpdateBatchStartTime)) || (!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['end_time'][$batchKey], $BeforeUpdateBatchEndTime)) || (!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['price'][$batchKey], $BeforeUpdateBatchPrice)) || (!in_array($_POST['ClassBatch']['ClassVenue'][$venueIndex]['seats'][$batchKey], $BeforeUpdateBatchSeats))) {
                                    $updateInformationClass[] = "Batch";
                                }
                            }
                            /*                             * *** ************ save batches early discount **************** */
                            if (isset($_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['valid_to'])) {
                                for ($k = 0; $k < count($_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['valid_to']); $k++) {
                                    if ($_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['valid_to'][$k] <> ""):
                                        $modelClassEarlyDiscount = new ClassEarlyDiscount;
                                        $modelClassEarlyDiscount->setAttribute('discount_price', $_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['discount_price'][$k]);
                                        $modelClassEarlyDiscount->setAttribute('in_percentage', $_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['in_percentage'][$k]);
                                        $modelClassEarlyDiscount->setAttribute('valid_to', $_POST['ClassEarlyDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['valid_to'][$k]);
                                        $modelClassEarlyDiscount->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                                        $modelClassEarlyDiscount->setAttribute('create_time', SkillConfig::CreateDateTime());
                                        $modelClassEarlyDiscount->setAttribute('class_batch_id', $modelClassBatch->id);
                                        $modelClassEarlyDiscount->setAttribute('classes_id', $model->id);
                                        $modelClassEarlyDiscount->save(false);
                                    endif;
                                }
                            }

                            /**                             * *********** save batches group discount **************** */
                            if (isset($_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['group_size'])) {
                                for ($k = 0; $k < count($_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['group_size']); $k++) {
                                    if ($_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['group_size'][$k] <> ""):
                                        $modelGroupDiscount = new GroupDiscount;
                                        $modelGroupDiscount->setAttribute('discount_amount', $_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['discount_amount'][$k]);
                                        $modelGroupDiscount->setAttribute('discount_in_percentage', $_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['discount_in_percentage'][$k]);
                                        $modelGroupDiscount->setAttribute('group_size', $_POST['GroupDiscount']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['group_size'][$k]);
                                        $modelGroupDiscount->setAttribute('status', SkillConfig::STATUS_ACTIVE);
                                        $modelGroupDiscount->setAttribute('create_time', SkillConfig::CreateDateTime());
                                        $modelGroupDiscount->setAttribute('class_batch_id', $modelClassBatch->id);
                                        $modelGroupDiscount->setAttribute('classes_id', $model->id);
                                        $modelGroupDiscount->save(false);

                                    endif;
                                }
                            }

                            /*                             * ************ save batches schedule Session **************** */
                            if (isset($_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['date'])) {
                                for ($k = 0; $k < count($_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['date']); $k++) {
                                    if ($_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['date'][$k] <> ""):
                                        $modelBatcheSession = new BatcheSession;
                                        $modelBatcheSession->setAttribute('date', $_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['date'][$k]);
                                        $modelBatcheSession->setAttribute('start_time', $_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['start_time'][$k]);
                                        $modelBatcheSession->setAttribute('end_time', $_POST['ClassScheduleSession']['ClassVenue'][$venueIndex]['ClassBatch'][$batchIndex]['end_time'][$k]);
                                        $modelBatcheSession->setAttribute('batche_id', $modelClassBatch->id);
                                        $modelBatcheSession->setAttribute('classes_id', $model->id);
                                        $modelBatcheSession->save(false);
                                    endif;
                                }
                            }
                            /*                             * ************************* save batches structure **************** */
                            if (isset($_POST['ClassStructures']['ClassBatch'][$batchIndex]['ClassVenue'][$venueIndex]['start_time'])) {
                                for ($k = 0; $k < count($_POST['ClassStructures']['ClassBatch'][$batchIndex]['ClassVenue'][$venueIndex]['start_time']); $k++) {
                                    if ($_POST['ClassStructures']['ClassBatch'][$batchIndex]['ClassVenue'][$venueIndex]['start_time'][$k] <> "" && $_POST['ClassStructures']['ClassBatch'][$batchIndex]['ClassVenue'][$venueIndex]['end_time'][$k] <> "" && $_POST['ClassStructures']['ClassBatch'][$batchIndex]['ClassVenue'][$venueIndex]['description'][$k] <> ""):
                                        $modelClassStructure = new ClassStructures;
                                        $modelClassStructure->setAttribute('start_time', $_POST['ClassStructures']['ClassBatch'][$batchIndex]['ClassVenue'][$venueIndex]['start_time'][$k]);
                                        $modelClassStructure->setAttribute('end_time', $_POST['ClassStructures']['ClassBatch'][$batchIndex]['ClassVenue'][$venueIndex]['end_time'][$k]);
                                        $modelClassStructure->setAttribute('description', $_POST['ClassStructures']['ClassBatch'][$batchIndex]['ClassVenue'][$venueIndex]['description'][$k]);
                                        $modelClassStructure->setAttribute('class_batch_id', $modelClassBatch->id);
                                        $modelClassStructure->setAttribute('classes_id', $model->id);
                                        $modelClassStructure->save(FALSE);
                                    endif;
                                }
                            }
                        }
                    }
                }
            }
        }

        if (!empty($updateInformationClass)) {
            $this->SendmailToUserByNewUpdateClassNotification($model, 'update', $updateInformationClass);
        }
    }

    private static function saveClassFunLearning($model) {
        (!$model->isNewRecord) ? Classes::deleteClassFunLearning($model->id) : '';
        $modelFunLearning = new FunLearning;
        if (isset($_POST['FunLearningValue'])) {
            $fun = $_POST['FunLearningValue']['fun'];
            $learn = SkillConfig::FUN_LEARING_LIMIT - $fun;
            $modelFunLearning->setAttribute('fun', $fun);
            $modelFunLearning->setAttribute('learn', $learn);
            $modelFunLearning->setAttribute('classes_id', $model->id);
            $modelFunLearning->setAttribute('status', 1);
            $modelFunLearning->setAttribute('create_time', SkillConfig::CreateDateTime());
            $modelFunLearning->save(FALSE);
        }
    }

    private static function saveClassTicketBooked($model) {
        (!$model->isNewRecord) ? Classes::deleteClassTicketBooked($model->id) : '';
        $modelTicketBooked = new TicketBooked;
        if (isset($_POST['TicketBooked'])) {
            $modelTicketBooked->setAttribute('no_of_days', $_POST['TicketBooked']['no_of_days']);
            $modelTicketBooked->setAttribute('no_of_hours', $_POST['TicketBooked']['no_of_hours']);
            $modelTicketBooked->setAttribute('classes_id', $model->id);
            $modelTicketBooked->setAttribute('action', $_POST['TicketBooked']['action']);
            $modelTicketBooked->save(FALSE);
        }
    }

    private static function addClassImage($model) {
        if (!empty($model->users_id)) {
            $uploadeDir = Yii::app()->getBasePath() . '/../' . getUploadDir()  . SkillConfig::getaftersaveClassCourseImagePath($model->users_id);
            $readUploadeDir = Yii::app()->getBasePath() . '/../' . getUploadDir() . SkillConfig::getClassCourseImagePath($model->users_id);
        } else {
            $uploadeDir = Yii::app()->getBasePath() . '/../' . getUploadDir() . SkillConfig::getaftersaveClassCourseImagePath('backend/' . getLoginUserId());
            $readUploadeDir = Yii::app()->getBasePath() . '/../' . getUploadDir() . SkillConfig::getClassCourseImagePath('backend/' . getLoginUserId());
        }
        $userImages = Yii::app()->user->getState('images');
        if (!empty($userImages)) {
            foreach ($userImages as $classImage) {
                $modelClassImage = new ClassImage;
                if (file_exists("$readUploadeDir" . $classImage['filename'])) {
                    copy("$readUploadeDir" . $classImage['filename'], $uploadeDir . $classImage['filename']);
                    unlink("$readUploadeDir" . $classImage['filename']);
                }

                if (Yii::app()->user->hasState('primaryImage')) {
                    $primaryImage = Yii::app()->user->getState('primaryImage');
                    if ($primaryImage == $classImage["filename"]) {
                        $updateModel = ClassImage::model()->find('classes_id=:classes_id AND primary_image=:primary_image', array(':classes_id' => $model->id, 'primary_image' => SkillConfig::STATUS_ACTIVE));
                        if (!empty($updateModel)) {
                            ClassImage::model()->updateByPk($updateModel->id, array('primary_image' => '0'));
                        }
                        $modelClassImage->primary_image = 1;
                    }
                }
                $modelClassImage->photo = $classImage["filename"];
                $modelClassImage->classes_id = $model->id;
                $modelClassImage->save(false);
            }
        }
    }

    public function actionCreate() {
        /* this code for user for asign workshop front end users */
        Yii::app()->user->setState('trainer_id', NULL);
        /* end */
        Yii::import("xupload.models.XUploadForm");
        $model = new Classes;
        $modelClassImage = new ClassImage;
        $modelClassStructures = new ClassStructures;
        $modelClassType = new ClassType;
        $modelClassVenue = new ClassVenue;
        $modelClassBatch = new ClassBatch;
        $modelClassEarlyDiscount = new ClassEarlyDiscount;
        $modelGroupDiscount = new GroupDiscount;
        $photos = new XUploadForm;
        $modelFunLearning = new FunLearning;
        $modelTicketBooked = new TicketBooked;
        $save = $this->saveClass($model, 'new');
        $this->render('create', array('model' => $model,
            'modelClassEarlyDiscount' => $modelClassEarlyDiscount,
            'modelClassImage' => $modelClassImage,
            'modelClassStructures' => $modelClassStructures,
            'modelClassVenue' => $modelClassVenue,
            'modelClassBatch' => $modelClassBatch,
            'modelGroupDiscount' => $modelGroupDiscount,
            'photos' => $photos,
            'modelFunLearning' => $modelFunLearning,
            'modelTicketBooked' => $modelTicketBooked,
        ));
    }

    public function actionUpdate($id) {
        $this->pageTitle = 'Update My Classe';
        $model = $this->loadModel($id, 'Classes');
        /* this code for user for asign workshop front end users */
        if (!empty($model->users_id)) {
            Yii::app()->user->setState('trainer_id', $model->users_id);
        }
        /* end */
        Yii::import("xupload.models.XUploadForm");
        $modelClassImage = new ClassImage;
        $modelClassStructures = new ClassStructures;
        $modelClassType = new ClassType;
        $modelClassVenue = new ClassVenue;
        $modelClassBatch = new ClassBatch;
        $modelClassEarlyDiscount = new ClassEarlyDiscount;
        $modelGroupDiscount = new GroupDiscount;
        $photos = new XUploadForm;
        $modelFunLearning = new FunLearning;
        $modelTicketBooked = new TicketBooked;
        $classWithVenue = new ClassWithVenue;
        $TicketCanBookedByClass = $modelTicketBooked->findByAttributes(array('classes_id' => $id));
        if ($TicketCanBookedByClass) {
            $modelTicketBooked = $this->loadModel($TicketCanBookedByClass->id, 'TicketBooked');
        }
        $this->saveClass($model, 'update');
        /* This is for all Venues With Class */
        $allVenuesWithClass = $classWithVenue->findAllByAttributes(array('classes_id' => $id));
        /* This is for all selected Venues With Class */
        $allVenueSelected = '';
        for ($i = 0; $i < count($allVenuesWithClass); $i++) {
            $allVenueSelected.= $allVenuesWithClass[$i]->class_venue_id . ',';
        }
        $allVenueSelected = trim($allVenueSelected, ",");
        $FunLearning = $modelFunLearning->findByAttributes(array('classes_id' => $id));
        if (count($FunLearning) > 0) {
            $modelFunLearning = $FunLearning;
        }


        $this->render('update', array(
            'model' => $model,
            'modelClassEarlyDiscount' => $modelClassEarlyDiscount,
            'modelClassImage' => $modelClassImage,
            'modelClassStructures' => $modelClassStructures,
            'modelClassVenue' => $modelClassVenue,
            'modelClassBatch' => $modelClassBatch,
            'modelGroupDiscount' => $modelGroupDiscount,
            'photos' => $photos,
            'modelFunLearning' => $modelFunLearning,
            'modelTicketBooked' => $modelTicketBooked,
            'modelclassWithVenue' => $classWithVenue,
            /* Values */
            'allVenues' => $allVenuesWithClass,
            'allVenueSelected' => $allVenueSelected,
        ));
    }

    public function actionDelete($id) {
        if (Yii::app()->getRequest()->getIsPostRequest()) {
            $modelClassStructures = new ClassStructures;
            $modelClassStructuresDetail = $modelClassStructures->findByAttributes(array('classes_id' => $id));
            $model = $this->loadModel($id, 'Classes');
            Classes::deleteClassesWithVenue($id);
            Classes::deleteClassesBatches($id);
            Classes::deleteClassesBatcheEarlyDiscount($id);
            Classes::deleteClassesBatcheGroupDiscount($id);
            Classes::deleteClassesBatcheSessions($id);
            Classes::deleteClassesStructure($id);
            Classes::deleteClassTicketBooked($id);
            Classes::deleteClassFunLearning($id);
            self::deleteClassImageByClassId($id);
            $this->loadModel($id, 'Classes')->delete();
            if (!Yii::app()->getRequest()->getIsAjaxRequest())
                $this->redirect(array('admin'));
        } else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Classes');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function actionAdmin() {
        $model = new Classes('search');
        $criteria = new CDbCriteria;
        $criteria->order = 'create_time DESC';
        $model->unsetAttributes();
        $statuschangeurl = Yii::app()->createUrl('classes/statuschange/');
        if (isset($_GET['Classes'])) {
            $model->setAttributes($_GET['Classes']);
            $criteria->compare('id', $model->id, true);
            $criteria->compare('class_titile', $model->class_titile, true);
            $criteria->compare('status', $model->status);
            $criteria->compare('create_time', $model->create_time, true);
            $criteria->compare('update_time', $model->update_time, true);
            $criteria->compare('class_type_id', $model->class_type_id);
            $criteria->compare('category_id', $model->category_id);
            if ($model->backend_user_id === '0') {
                $criteria->addCondition(array('condition' => 'backend_user_id is null'));
            } else {
                $criteria->compare('backend_user_id', $model->backend_user_id, true);
            }
        }
        $DataProvider = new CActiveDataProvider($model, array('criteria' => $criteria));
        $this->render('admin', array(
            'DataProvider' => $DataProvider,
            'model' => $model,
            'statuschangeurl' => $statuschangeurl,
        ));
    }

    public function actionStatuschange() {
        $model = $this->loadModel($_POST['id'], 'Classes');
        $model->status = $_POST['status'];
        $model->save();
    }

    public function actionUpload() {
        Yii::import("xupload.models.XUploadForm");
        $frontUser = (Yii::app()->user->hasState('trainer_id')) ? Yii::app()->user->getState('trainer_id') : '';
        $folder = (!empty($frontUser)) ? getUploadDir() . $frontUser : getUploadDirBackend() . getLoginUserId();
        $dirUser = $folder;
        $dirClassCourse = $dirUser . '/class-course-image';
        $dirClassCourseThumb = $dirUser . '/class-course-image/thumbs';
        /* Create directory */
        if (!is_dir($dirUser)) {
            makeUploadDir("backend");
        }
        $publicPath = Yii::app()->getBaseUrl() . '/../../' . $dirClassCourseThumb . '/';
        $path = $dirClassCourse . '/';
        header('Vary: Accept');
        if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
            header('Content-type: application/json');
        } else {
            header('Content-type: text/plain');
        }
        if (isset($_GET["_method"])) {
            if ($_GET["_method"] == "delete") {
                if ($_GET["file"][0] !== '.') {
                    $file = $path . $_GET["file"];
                    if (is_file($file)) {
                        unlink($file);
                    }
                }
                echo json_encode(true);
            }
        } else {
            $model = new XUploadForm;
            $model->file = CUploadedFile::getInstance($model, 'file');
            if ($model->file !== null) {
                $filenameExt = '';
                $model->mime_type = $model->file->getType();
                $model->size = $model->file->getSize();
                $model->name = $model->file->getName();
//(optional) Generate a random name for our file
                $filename = md5(Yii::app()->user->id . microtime() . $model->name);
                $filenameExt.= "." . $model->file->getExtensionName();
                $newFilename = $filename . $filenameExt;
                if ($model->validate()) {
                    $model->file->saveAs($path . $newFilename);
                    $newimage = $path . $newFilename;
                    $image = Yii::app()->image->load($newimage);
                    $image->resize(CLASS_IMAGE_WIDTH, CLASS_IMAGE_HEIGHT, Image::NONE);
                    $image->save($path . '/thumbs/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $detailsimage = Yii::app()->image->load($newimage);
                    $detailsimage->resize(CLASS_IMAGE_DETAILS_WIDTH, CLASS_IMAGE_DETAILS_HEIGHT, Image::NONE);
                    $detailsimage->save($path . '/details-image/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $sliderimage = Yii::app()->image->load($newimage);
                    $sliderimage->resize(CLASS_IMAGE_SLIDER_WIDTH, CLASS_IMAGE_SLIDER_HEIGHT, Image::NONE);
                    $sliderimage->save($path . '/slider-image/' . $newFilename);
                    chmod($path . $newFilename, 0777);
                    $userListImage = Yii::app()->image->load($newimage);
                    $userListImage->resize(CLASS_IMAGE_USERLIST_WIDTH, CLASS_IMAGE_USERLIST_HEIGHT, Image::NONE);
                    $userListImage->save($path . '/240X180/' . $newFilename);
                    chmod($path . $newFilename, 0777);

                    if (Yii::app()->user->hasState('images')) {
                        $userImages = Yii::app()->user->getState('images');
                    } else {
                        $userImages = array();
                    }
                    $userImages[] = array(
                        "path" => $path . $newFilename,
                        "thumb" => $path . '/thumbs/' . $newFilename,
                        "filename" => $newFilename,
                        'size' => $model->size,
                        'mime' => $model->mime_type,
                        'name' => $model->name,
                    );
                    Yii::app()->user->setState('images', $userImages);
                    echo json_encode(array(array(
                            "name" => $model->name,
                            "type" => $model->mime_type,
                            "size" => $model->size,
                            "url" => $publicPath . $newFilename,
                            "thumbnail_url" => $publicPath . $newFilename,
                            "delete_url" => $this->createUrl("upload", array(
                                "_method" => "delete",
                                "file" => $newFilename
                            )),
                            "delete_type" => "POST"
                            )));
                } else {
//If the upload failed for some reason we log some data and let the widget know
                    echo json_encode(array(
                        array("error" => $model->getErrors('file'),
                            )));
                    Yii::log("XUploadAction: " . CVarDumper::dumpAsString($model->getErrors()), CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
                    );
                }
            } else {
                throw new CHttpException(500, "Could not upload file");
            }
        }
    }

    public function actionmakePrimaryImage() {
        Yii::app()->user->setState('primaryImage', NULL);
        $imagename = $_POST['imagename'];
        $newImagename = explode('/', $imagename);
        Yii::app()->user->setState('primaryImage', end($newImagename));
    }

    public function actiongetAllCountry() {
        $data = Country::model()->findAllByAttributes(array('is_active' => SkillConfig::STATUS_ACTIVE));
        $data = CHtml::listData($data, 'id', 'name');
        echo CHtml::tag('option', array('value' => ''), CHtml::encode('Select Country Name'), true);
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value, 'selected' => ($value == SkillConfig::ACTIVE_COUNTRY) ? 'selected' : ''), CHtml::encode($name), true);
        }
    }

    public function actiongetAllVenue() {
        $frontUser = (Yii::app()->user->hasState('trainer_id')) ? Yii::app()->user->getState('trainer_id') : '';
        if (!empty($frontUser)) {
            $data = ClassVenue::model()->findAll('users_id=:users_id', array(':users_id' => (int) $frontUser));
        } else {
            $data = ClassVenue::model()->findAll('backend_user_id=:backend_user_id', array(':backend_user_id' => (int) getLoginUserId()));
        }

        $data = CHtml::listData($data, 'id', 'name');
        echo CHtml::tag('option', array('value' => ''), CHtml::encode('Select Venue Name'), true);
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }

    public function actiondynamicState() {
        $data = State::model()->findAll('country_id=:country_id AND is_active=:is_active', array(':country_id' => (int) $_POST['countryId'], 'is_active' => SkillConfig::STATUS_ACTIVE));
        $data = CHtml::listData($data, 'id', 'name');
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value, 'selected' => ($value == SkillConfig::ACTIVE_STATE) ? 'selected' : ''), CHtml::encode($name), true);
        }
    }

    public function actiondynamicCity() {
        $data = City::model()->findAll('state_id=:state_id AND status=:status', array(':state_id' => (int) $_POST['stateId'], 'status' => SkillConfig::STATUS_ACTIVE));
        $data = CHtml::listData($data, 'id', 'city_name');
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value, 'selected' => ($value == SkillConfig::ACTIVE_CITY) ? 'selected' : ''), CHtml::encode($name), true);
        }
    }

    public function actionSelectedVenue() {
        $data = ClassVenue::model()->find('id=:id AND status=:status', array(':id' => (int) $_POST['venueId'], 'status' => SkillConfig::STATUS_ACTIVE));
        echo CJSON::encode($data);
    }

    public function actiongetAllState() {
        $data = State::model()->findAllByAttributes(array('is_active' => SkillConfig::STATUS_ACTIVE));
        $data = CHtml::listData($data, 'id', 'name');
        echo CHtml::tag('option', array('value' => ''), CHtml::encode('Select State Name'), true);
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value, 'selected' => ($value == SkillConfig::ACTIVE_STATE) ? 'selected' : ''), CHtml::encode($name), true);
        }
    }

    public function actiongetAllCity() {
        $data = City::model()->findAllByAttributes(array('status' => SkillConfig::STATUS_ACTIVE));
        $data = CHtml::listData($data, 'id', 'city_name');
        echo CHtml::tag('option', array('value' => ''), CHtml::encode('Select City Name'), true);
        foreach ($data as $value => $name) {
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }

    public function actionprimaryImage() {
        $updateModel = ClassImage::model()->find('classes_id=:classes_id AND primary_image=:primary_image', array(':classes_id' => (int) $_POST['classid'], 'primary_image' => SkillConfig::STATUS_ACTIVE));
        if (!empty($updateModel)) {
            ClassImage::model()->updateByPk($updateModel->id, array('primary_image' => '0'));
        }
        $model = $this->loadModel($_POST['id'], 'ClassImage');
        $model->primary_image = '1';
        $model->save();
    }

    public function actiondeleteClassImage() {
        $uploadeDir = Yii::app()->getBasePath() . '/../' . getUploadDir() . SkillConfig::getClassCourseImagePath('backend/' . getLoginUserId());
        $idList = Yii::app()->request->getParam('idList');
        $allIds = (is_array($idList)) ? implode(',', $idList) : $idLsit;
        $classImageId = explode(',', $allIds);
        for ($i = 0; $i < count($classImageId); $i++) {
            $imageName = ClassImage::model()->find('id=:id ', array(':id' => (int) $classImageId[$i]));
            if (file_exists("$uploadeDir" . 'details-image/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'details-image/' . $imageName->photo);
            }
            if (file_exists("$uploadeDir" . 'image/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'image/' . $imageName->photo);
            }
            if (file_exists("$uploadeDir" . 'slider-image/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'slider-image/' . $imageName->photo);
            }
            if (file_exists("$uploadeDir" . 'thumbs/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'thumbs/' . $imageName->photo);
            }
            if (file_exists("$uploadeDir" . '240X180/' . $imageName->photo)) {
                unlink("$uploadeDir" . 'thumbs/' . $imageName->photo);
            }
            if (file_exists("$uploadeDir" . $imageName->photo)) {
                unlink("$uploadeDir" . $imageName->photo);
            }
        }

        $sql = "DELETE FROM skill_class_image WHERE id IN($allIds)";
        $cmd = Yii::app()->db->createCommand($sql);
        $cmd->execute();
        $this->actionIndex();
    }

    public function deleteClassImageByClassId($id) {
        $model = $this->loadModel($id, 'Classes');
        if ($model->backend_user_id <> "") {
            $folderClassCouse = 'backend/' . getLoginUserId();
        } else {
            $folderClassCouse = $model->users_id;
        }
        $uploadeDir = Yii::app()->getBasePath() . '/../' . getUploadDir() . SkillConfig::getClassCourseImagePath($folderClassCouse);
        $allIds = '';
        $allImagesClass = ClassImage::model()->findAllByAttributes(array('classes_id' => $id));
        if (count($allImagesClass) > 0) {
            for ($i = 0; $i < count($allImagesClass); $i++) {
                $allIds.= $allImagesClass[$i]->id . ',';
            }
            $allIds = trim($allIds, ",");
            $classImageId = explode(',', $allIds);
            for ($i = 0; $i < count($classImageId); $i++) {
                $imageName = ClassImage::model()->find('id=:id ', array(':id' => (int) $classImageId[$i]));
                if (file_exists("$uploadeDir" . 'details-image/' . $imageName->photo)) {
                    unlink("$uploadeDir" . 'details-image/' . $imageName->photo);
                }
                if (file_exists("$uploadeDir" . 'image/' . $imageName->photo)) {
                    unlink("$uploadeDir" . 'image/' . $imageName->photo);
                }
                if (file_exists("$uploadeDir" . 'slider-image/' . $imageName->photo)) {
                    unlink("$uploadeDir" . 'slider-image/' . $imageName->photo);
                }
                if (file_exists("$uploadeDir" . 'thumbs/' . $imageName->photo)) {
                    unlink("$uploadeDir" . 'thumbs/' . $imageName->photo);
                }
            }

            $sql = "DELETE FROM skill_class_image WHERE id IN($allIds)";
            $cmd = Yii::app()->db->createCommand($sql);
            $cmd->execute();
        }
    }

    public function actionStarRatingAjax() {
        $ratingAjax = isset($_POST['rate']) ? $_POST['rate'] : 0;
        echo $ratingAjax;
    }

    private function SendmailToUserByNewUpdateClassNotification($model, $recordtype, $updateInformationClass) {
        $updateInfo = '';
        if (!empty($model->backend_user_id)) {
            $userNames = Users::getBackEndUser($model->backend_user_id);
            $subscribeUsers = TrainerFollow::model()->findAll('trainer_front_end_user_id=' . $model->backend_user_id);
        } else {
            $subscribeUsers = TrainerFollow::model()->findAll('trainer_front_end_user_id=' . $model->users_id);
            $userNames = Users::getFrontEndUser($model->users_id);
        }
        $trainnername = $userNames->first_name . '  ' . $userNames->last_name;
        $classCourseName = $model->class_titile;
        $viewClassLink = SITE_URL . 'classes/viewClass/id/' . $model->id;

        if ($recordtype == "new" && $updateInformationClass == "") {
            if (!empty($subscribeUsers)) {
                foreach ($subscribeUsers as $subscribeUser) {
                    $follwersName = Users::model()->findByPk($subscribeUser->folower_user_id);
                    $mailmodel = EmailTemplate::model()->findByPk(Message::CREATE_CLASS_COURSE_SUBSCRIBE_USER_NOTIFICATION);
                    $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
                    $subject = $mailmodel->subject;
                    $mailto = $follwersName->username;
                    $arrayFind = array('[username]', '[trainer_name]', '[classcoursename]', '[classCourseViewdetailsLink]');
                    $arrayReplace = array($mailto, $trainnername, $classCourseName, $viewClassLink);
                    $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                    $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                    $subject = $mailmodel->subject;
                    $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                    try {
                        SkillSendMail::SendMail($mailto, $subject, $body);
                    } catch (Exception $e) {
                        echo $e;
                        exit;
                    }
                }
            }
        } else {
            $updateInformationClass = array_unique($updateInformationClass);
            foreach ($updateInformationClass as $key => $value) {
                $updateInfo.='<li>' . $updateInformationClass[$key] . '</lI>';
            }
            $updateInfo = '<ul>' . $updateInfo . '</ul>';
            $template = Message::UPDATECLASS_TEMPLATE_NOTIFICATION;
            $allSubscriber = MakeQuery::model()->findAllByAttributes(array('classes_id' => $model->id));

            $mailmodel = EmailTemplate::model()->findByPk($template);
            $mailbody = array('value' => $mailmodel->body, 'type' => 'raw');
            $mailtemp = Template::model()->findByPk($mailmodel->template_id);
            if (count($allSubscriber) > 0) {
                foreach ($allSubscriber as $allSubscriberUser) {
                    $mailto = $allSubscriberUser->email;
                    $userName = $allSubscriberUser->name;
                    $arrayFind = array('[username]', '[trainer_name]', '[updateclass]', '[classcoursename]', '[classCourseViewdetailsLink]');
                    $arrayReplace = array($userName, $trainnername, $updateInfo, $classCourseName, $viewClassLink);
                    $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                    $subject = $mailmodel->subject;
                    $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                    try {
                        SkillSendMail::SendMail($mailto, $subject, $body);
                    } catch (Exception $e) {
                        echo $e;
                        exit;
                    }
                }
            }
        }
    }

    public function actionviewcontent($classid) {
        $dataProvider = new CActiveDataProvider('ClassCourseContentLikeUnlike', array(
                    'criteria' => array(
                        'condition' => 'classes_id=' . $classid,
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                    ),
                ));
        $this->render('viewcontentrate', array(
            'model' => $dataProvider, 'classid' => $classid
        ));
    }

    public function actionasigntotrainner() {
        $model = new Classes;
        if (isset($_POST['yt0']) || isset($_POST['yt1'])) {
            if (!empty($_POST['Classes']['users_id'])) {
                Yii::app()->user->setState('trainer_id', $_POST['Classes']['users_id']);
            } else {
                Yii::app()->user->setState('trainer_id', NULL);
            }
            $this->redirect(array('create'));
        }
        $this->render('_asigntotrainer', array('model' => $model));
    }

}

